<script setup>
import { ref } from 'vue';
import axios from 'axios';

const loginForm = ref({
  username: 'admin',
  password: '123456',
  captcha: ''
});

const captchaUrl = ref('');
const showCaptchaButton = ref(true); // 控制按钮显示与隐藏

const getCaptcha = async () => {
  if (loginForm.value.username) {
    try {
      const response = await axios.get(`http://localhost:8000/api/generate-code-image?username=${loginForm.value.username}`, {
        responseType: 'arraybuffer' // 设置响应类型为 arraybuffer
      });
      const uint8Array = new Uint8Array(response.data);
      const base64String = btoa(String.fromCharCode.apply(null, uint8Array));
      captchaUrl.value = `data:image/png;base64,${base64String}`;
      showCaptchaButton.value = false; // 验证码显示后隐藏按钮
    } catch (error) {
      console.error('获取验证码失败:', error);
    }
  } else {
    alert('请输入用户名');
  }
};

const submitForm = async () => {
  try {
    // 打印表单值用于调试
    console.log(loginForm.value);


    // 先验证验证码
    const verifyCodeResponse = await axios.post(`http://localhost:8000/api/verify-code?username=${loginForm.value.username}&code=${loginForm.value.captcha}`);

    console.log('验证码验证响应:', verifyCodeResponse.data);

    if (verifyCodeResponse.data === '验证码有效') {
      // 验证码验证通过，再验证用户名和密码
      const response = await axios.get('http://localhost:8000/getuser');

      // 处理服务器返回的数据
      const users = response.data;

      // 检查登录表单中的值是否与后端返回的数据匹配
      const matchedUser = users.find(user => 
        user.username === loginForm.value.username && 
        user.password === loginForm.value.password
      );

      if (matchedUser) {
        alert('登录成功');
        const tokenMap = await axios.get('http://localhost:8000/getToken');
        const token = tokenMap.data.token;
        // 存储token和userId到本地存储中
        window.localStorage.setItem('token', token);
        window.localStorage.setItem('userId', matchedUser.id);

        // 跳转到首页
        window.location.href = '/#/article';
      } else {
        alert('用户名或密码不匹配');
      }
    } else {
      alert('验证码不正确或已过期');
    }
  } catch (error) {
    // 错误处理
    console.error('请求失败:', error);
  }
};

const resetForm = () => {
  loginForm.value.username = '';
  loginForm.value.password = '';
  loginForm.value.captcha = '';
  captchaUrl.value = '';
  showCaptchaButton.value = true; // 重置表单时显示按钮
};
</script>

<template>
  <div>
    <div class="fullscreen-background">
      <div class="login-container">
        <h3 class="title">登录</h3>
        <form @submit.prevent="submitForm">
          <div class="input-group">
            <label for="username">用户名</label>
            <input id="username" v-model="loginForm.username" type="text" placeholder="请输入用户名" required>
          </div>
          <div class="input-group">
            <label for="password">密码</label>
            <input id="password" v-model="loginForm.password" type="password" placeholder="请输入密码" required>
          </div>
          <div class="input-group">
            <label for="captcha">验证码</label>
            <div class="captcha-container">
              <input id="captcha" v-model="loginForm.captcha" type="text" placeholder="请输入验证码" required>
              <button type="button" @click="getCaptcha" v-if="showCaptchaButton">获取验证码</button>
              <img :src="captchaUrl" alt="验证码" v-if="captchaUrl" />
            </div>
          </div>
          <div class="button-group">
            <button type="submit" class="submit-button">登录</button>
            <button type="button" @click="resetForm">重置</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.fullscreen-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh; /* 使用 vh 单位确保高度适应视口 */
  background-image: url('@/assets/images/bg.jpg'); /* 替换为你的图片路径 */
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover; /* 使图片覆盖整个容器 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  height: 300px;
  width: 300px;
  background-color: white;
}

.title {
  text-align: center;
  margin-bottom: 10px;
}

.input-group {
  margin-bottom: 10px;
  width: 100%;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
}

.input-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.captcha-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.submit-button,
button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
}

button {
  background-color: #f0f0f0;
  color: #333;
}
</style>